package com.lhc.controller;

import com.lhc.controller.viewObject.ItemVo;
import com.lhc.error.BusniessException;
import com.lhc.response.CommonReturnType;
import com.lhc.service.ItemService;
import com.lhc.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Controller("item")
@RequestMapping("/item")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class ItemController extends BaseController{
    @Autowired
    private ItemService itemService;

    @RequestMapping(value = "/getItemById",method = RequestMethod.GET)
    @ResponseBody
    public CommonReturnType getItemById(@RequestParam("id") Integer id){
        ItemModel itemById = itemService.getItemById(id);
        ItemVo itemVo = this.convertFromItemModel(itemById);
        return  CommonReturnType.create(itemVo);
    }
    @RequestMapping(value = "/getItemList",method = RequestMethod.GET)
    @ResponseBody
    public CommonReturnType getItemList(){
        List<ItemModel> itemModels = itemService.listItem();
        List<ItemVo> itemVoList = itemModels.stream().map(itemModel -> {
            ItemVo itemVo = this.convertFromItemModel(itemModel);
            return itemVo;
        }).collect(Collectors.toList());
        return CommonReturnType.create(itemVoList);
    }

    @RequestMapping(value = "/createItem",method = RequestMethod.POST,consumes = CONTENT_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType createItem(
            @RequestParam("title") String title,
            @RequestParam("price") BigDecimal price,
            @RequestParam("stock") Integer stock,
            @RequestParam("description") String description,
            @RequestParam("imgUrl") String imgUrl
    ) throws BusniessException {
        ItemModel itemModel = new ItemModel();
        itemModel.setTitle(title);
        itemModel.setPrice(price);
        itemModel.setStock(stock);
        itemModel.setDescription(description);
        itemModel.setImgUrl(imgUrl);
        ItemModel item = itemService.createItem(itemModel);
        ItemVo itemVo = this.convertFromItemModel(item);
        return CommonReturnType.create(itemVo);
    }

    private ItemVo convertFromItemModel(ItemModel itemModel){
        ItemVo itemVo = new ItemVo();
        if (itemModel == null){
            return null;
        }
        BeanUtils.copyProperties(itemModel,itemVo);
        return itemVo;
    }

}
